package cn.kent.nio.byteBuffer;

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

import static cn.kent.nio.byteBuffer.util.ByteBufferUtil.debugAll;

/**
 * 将字符串转为ByteBuffer的三种写法
 * 1. 转为byte直接写入
 * 2. Charset的encode方法会直接返回ByteBuffer，该方法本质还是warp方法
 * 3. ByteBuffer的warp方法
 */
public class TestByteBufferString {
    public static void main(String[] args) {
        // 1.将字符串转为ByteBuffer
        final ByteBuffer buffer = ByteBuffer.allocate(16);
        buffer.put("hello".getBytes());
        debugAll(buffer);

        // 2.Charset
        final ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("hello");
        debugAll(buffer2);

        final String str = StandardCharsets.UTF_8.decode(buffer2).toString();
        System.out.println(str);

        // 3. wrap
        final ByteBuffer buffer3 = ByteBuffer.wrap("hello".getBytes());
        debugAll(buffer3);

        final String str3 = StandardCharsets.UTF_8.decode(buffer3).toString();
        System.out.println("buffer3 -> " + str3);
    }
}
